package com.liangdemo.web.controller.login;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liangdemo.web.Service.UserService;
import com.liangdemo.web.Service.impl.AccoutService;
import com.liangdemo.web.model.Account;
import com.liangdemo.web.model.DTO.LoginDTO;
import com.liangdemo.web.model.DTO.RegisterDTO;
import com.liangdemo.web.model.User;
import com.liangdemo.web.token.JwtUtils;
import com.liangdemo.web.utils.ajax.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


/**
 * 登录
 *
 * @author Mr.Liang
 * @date 2022/4/25 11:49
 */
@Controller
@ResponseBody
public class LoginController {
    @Autowired
    private AccoutService accoutService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;


    @GetMapping("/login")
    public AjaxResult login(LoginDTO loginDTO) {
        Map<String, Object> map = new HashMap<>();
        if (loginDTO.getAccount().isEmpty() && loginDTO.getPassword().isEmpty()) {
            //返回为空的错误信息
        }
        loginDTO.setPassword(DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes(StandardCharsets.UTF_8)));
        //根据账号密码获取用户id
        Account account = accoutService.getOne(new LambdaQueryWrapper<Account>().eq(Account::getAccount, loginDTO.getAccount()).eq(Account::getPassword, loginDTO.getPassword()));
        //根据用户id获取用户信息
        User user = userService.getById(account.getUserId());
        //根据用户信息生成token并返回
        String token = jwtUtils.createJwt(user.getId(), user.getUserName());
        map.put("token", token);
        return AjaxResult.success(map);

    }

    /**
     * 根据token获取用户信息
     * @param request
     *
     * @return
     */
    @GetMapping("/token")
    public AjaxResult jtoken(HttpServletRequest request) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String token = httpRequest.getHeader("token");
        String id = jwtUtils.parseJwt(token).getId();
        User user = userService.getById(id);
        return AjaxResult.success(jwtUtils.parseJwt(token));
    }

    /**
     * 用户注册
     *
     * @return
     */
    @GetMapping("/add")
    public String Add(RegisterDTO registerDTO) {
        return accoutService.register(registerDTO);
    }


}
